package fr.upmc.cie.xml;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;

import org.xml.sax.SAXException;

import android.sax.Element;
import android.sax.EndElementListener;
import android.sax.EndTextElementListener;
import android.sax.RootElement;
import android.util.Xml;

import fr.upmc.cie.data.ChannelItem;
import fr.upmc.cie.data.TicketItem;

public class AndroidSaxFeedParser extends BaseFeedParser {

	public AndroidSaxFeedParser(String feedUrl) throws MalformedURLException {
		super(feedUrl);
	}

	@Override
	public ArrayList<TicketItem> parseItem() throws IOException, SAXException {
		final TicketItem currentTicket = new TicketItem();
		RootElement root = new RootElement("rss");
		final ArrayList<TicketItem> tickets = new ArrayList<TicketItem>();
		Element channel = root.getChild("channel");
		channel.getChild(TITLE).setEndTextElementListener(new EndTextElementListener(){
			public void end(String body) {
				currentTicket.setSource(body);
			}
		});
		
		Element item = channel.getChild(ITEM);
		item.setEndElementListener(new EndElementListener(){
			public void end() {
				TicketItem ticket = new TicketItem(currentTicket);				
				tickets.add(ticket);
			}
		});
		item.getChild(TITLE).setEndTextElementListener(new EndTextElementListener(){
			public void end(String body) {
				currentTicket.setTitle(body);
			}
		});
		item.getChild(LINK).setEndTextElementListener(new EndTextElementListener(){
			public void end(String body) {
				currentTicket.setLink(body);
			}
		});
		item.getChild(DESCRIPTION).setEndTextElementListener(new 
				EndTextElementListener(){
			public void end(String body) {
				currentTicket.setContent(body);
			}
		});
		item.getChild(PUB_DATE).setEndTextElementListener(new EndTextElementListener(){
			public void end(String body) {
				currentTicket.setDate(body);
			}
		});
			Xml.parse(this.getInputStream(), Xml.Encoding.UTF_8, 
					root.getContentHandler());

		return tickets;
	}

	@Override
	public ChannelItem parseChannel() throws IOException, SAXException {
		final ChannelItem channelItem = new ChannelItem();
		RootElement root = new RootElement("rss");
		Element channel = root.getChild("channel");
		channel.getChild(TITLE).setEndTextElementListener(new EndTextElementListener(){
			public void end(String body) {
				channelItem.setTitle(body);
			}
		});
		
		channel.getChild(LINK).setEndTextElementListener(new EndTextElementListener(){
			public void end(String body) {
				channelItem.setUrl(body);
			}
		});
		Xml.parse(this.getInputStream(), Xml.Encoding.UTF_8, 
					root.getContentHandler());
		
		return channelItem;
	}

}
